"""
大麦网自动化服务
"""
import time
import json
import random
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
from pathlib import Path
import logging

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException

from ..utils.logger import ticket_logger
from ..utils.config import config

class DamaiService:
    """大麦网自动化服务类"""
    
    def __init__(self):
        self.driver = None
        self.wait = None
        self.logged_in = False
        self.current_user = None
        self.logger = ticket_logger
        
    def setup_driver(self, headless: bool = False) -> bool:
        """设置浏览器驱动"""
        try:
            options = webdriver.ChromeOptions()
            
            # 基本配置
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--disable-gpu')
            options.add_argument('--disable-blink-features=AutomationControlled')
            options.add_experimental_option("excludeSwitches", ["enable-automation"])
            options.add_experimental_option('useAutomationExtension', False)
            
            if headless:
                options.add_argument('--headless')
            
            # 设置窗口大小
            window_size = config.get('browser.window_size', [1920, 1080])
            options.add_argument(f'--window-size={window_size[0]},{window_size[1]}')
            
            # 设置用户代理
            user_agent = config.get('browser.user_agent')
            if user_agent:
                options.add_argument(f'--user-agent={user_agent}')
            
            self.driver = webdriver.Chrome(options=options)
            self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            
            self.wait = WebDriverWait(self.driver, 10)
            self.logger.info("浏览器驱动初始化成功")
            return True
            
        except Exception as e:
            self.logger.error(f"浏览器驱动初始化失败: {e}")
            return False
    
    def login(self, username: str, password: str) -> Dict[str, any]:
        """登录大麦网"""
        try:
            if not self.driver:
                if not self.setup_driver():
                    return {"success": False, "message": "浏览器初始化失败"}
            
            # 访问登录页面
            self.driver.get("https://passport.damai.cn/login")
            time.sleep(2)
            
            # 等待页面加载
            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "login-box")))
            
            # 输入用户名
            username_input = self.wait.until(
                EC.presence_of_element_located((By.ID, "fm-login-id"))
            )
            username_input.clear()
            username_input.send_keys(username)
            
            # 输入密码
            password_input = self.wait.until(
                EC.presence_of_element_located((By.ID, "fm-login-password"))
            )
            password_input.clear()
            password_input.send_keys(password)
            
            # 检查是否需要验证码
            try:
                slider = self.driver.find_element(By.CLASS_NAME, "fm-btn")
                if slider:
                    # 模拟滑动验证（需要根据实际情况调整）
                    self.logger.info("检测到滑动验证，请手动完成")
                    time.sleep(10)  # 给用户时间完成验证
            except:
                pass
            
            # 点击登录按钮
            login_button = self.wait.until(
                EC.element_to_be_clickable((By.CLASS_NAME, "fm-button"))
            )
            login_button.click()
            
            # 等待登录完成
            time.sleep(5)
            
            # 检查登录状态
            if "www.damai.cn" in self.driver.current_url:
                self.logged_in = True
                self.current_user = username
                self.logger.info(f"用户 {username} 登录成功")
                
                # 保存登录状态截图
                self.take_screenshot("login_success")
                
                return {
                    "success": True,
                    "message": "登录成功",
                    "user": {"username": username}
                }
            else:
                self.logger.error("登录失败，仍在登录页面")
                return {"success": False, "message": "登录失败，请检查用户名密码"}
                
        except TimeoutException:
            self.logger.error("登录超时")
            return {"success": False, "message": "登录超时，请重试"}
        except Exception as e:
            self.logger.error(f"登录异常: {e}")
            return {"success": False, "message": f"登录异常: {str(e)}"}
    
    def search_shows(self, keyword: str) -> Dict[str, any]:
        """搜索演出"""
        try:
            if not self.logged_in:
                return {"success": False, "message": "请先登录"}
            
            # 访问搜索页面
            search_url = f"https://search.damai.cn/searchajax.html?keyword={keyword}"
            self.driver.get(search_url)
            time.sleep(2)
            
            # 获取搜索结果
            page_source = self.driver.page_source
            try:
                # 尝试解析JSON响应
                json_start = page_source.find('{')
                json_end = page_source.rfind('}') + 1
                if json_start != -1 and json_end != -1:
                    json_str = page_source[json_start:json_end]
                    data = json.loads(json_str)
                    
                    shows = []
                    for item in data.get('data', {}).get('resultData', []):
                        show = {
                            "id": item.get('id', ''),
                            "name": item.get('name', ''),
                            "description": item.get('description', ''),
                            "date": item.get('showtime', ''),
                            "time": item.get('showtime', ''),
                            "venue": item.get('venue', ''),
                            "address": item.get('address', ''),
                            "city": item.get('cityname', ''),
                            "category": item.get('categoryname', ''),
                            "poster": item.get('verticalPic', ''),
                            "min_price": int(item.get('price', '0').split('-')[0].replace('¥', '')),
                            "max_price": int(item.get('price', '0').split('-')[-1].replace('¥', '')),
                            "status": item.get('status', ''),
                            "tags": item.get('tags', [])
                        }
                        shows.append(show)
                    
                    return {"success": True, "shows": shows}
            except:
                pass
            
            # 如果JSON解析失败，尝试页面解析
            self.driver.get(f"https://search.damai.cn/search.htm?keyword={keyword}")
            time.sleep(3)
            
            shows = []
            show_elements = self.driver.find_elements(By.CLASS_NAME, "search__item")
            
            for element in show_elements[:10]:  # 限制结果数量
                try:
                    name = element.find_element(By.CLASS_NAME, "search__item__name").text
                    venue = element.find_element(By.CLASS_NAME, "search__item__venue").text
                    date = element.find_element(By.CLASS_NAME, "search__item__time").text
                    price = element.find_element(By.CLASS_NAME, "search__item__price").text
                    
                    show = {
                        "id": element.get_attribute("data-id"),
                        "name": name,
                        "description": "",
                        "date": date,
                        "time": date,
                        "venue": venue,
                        "address": "",
                        "city": "",
                        "category": "",
                        "poster": "",
                        "min_price": int(price.replace('¥', '').split('-')[0]),
                        "max_price": int(price.replace('¥', '').split('-')[-1]),
                        "status": "在售",
                        "tags": []
                    }
                    shows.append(show)
                except:
                    continue
            
            return {"success": True, "shows": shows}
            
        except Exception as e:
            self.logger.error(f"搜索演出失败: {e}")
            return {"success": False, "message": f"搜索失败: {str(e)}"}
    
    def get_show_details(self, show_id: str) -> Dict[str, any]:
        """获取演出详情"""
        try:
            if not self.logged_in:
                return {"success": False, "message": "请先登录"}
            
            # 访问演出详情页
            self.driver.get(f"https://detail.damai.cn/item.htm?id={show_id}")
            time.sleep(3)
            
            # 获取演出信息
            show = {
                "id": show_id,
                "name": "",
                "description": "",
                "date": "",
                "time": "",
                "venue": "",
                "address": "",
                "city": "",
                "category": "",
                "poster": "",
                "min_price": 0,
                "max_price": 0,
                "status": "",
                "tags": [],
                "sessions": [],
                "price_ranges": []
            }
            
            try:
                # 获取基本信息
                show["name"] = self.driver.find_element(By.CLASS_NAME, "item-title").text
                show["description"] = self.driver.find_element(By.CLASS_NAME, "item-desc").text
                
                # 获取场次信息
                session_elements = self.driver.find_elements(By.CLASS_NAME, "perform__item")
                for element in session_elements:
                    session = {
                        "id": element.get_attribute("data-id"),
                        "show_id": show_id,
                        "date": element.find_element(By.CLASS_NAME, "perform__item__time").text,
                        "time": element.find_element(By.CLASS_NAME, "perform__item__time").text,
                        "description": element.text,
                        "status": "available",
                        "total_tickets": 0,
                        "available_tickets": 0
                    }
                    show["sessions"].append(session)
                
                # 获取价位信息
                price_elements = self.driver.find_elements(By.CLASS_NAME, "price__item")
                for element in price_elements:
                    price_range = {
                        "id": element.get_attribute("data-id"),
                        "show_id": show_id,
                        "session_id": "",
                        "range_name": element.text,
                        "price": int(element.get_attribute("data-price")),
                        "available_count": 0,
                        "total_count": 0
                    }
                    show["price_ranges"].append(price_range)
                
            except Exception as e:
                self.logger.warning(f"解析演出详情时出错: {e}")
            
            return {"success": True, "show": show}
            
        except Exception as e:
            self.logger.error(f"获取演出详情失败: {e}")
            return {"success": False, "message": f"获取详情失败: {str(e)}"}
    
    def rush_ticket(self, config: Dict[str, any]) -> Dict[str, any]:
        """抢票主逻辑"""
        try:
            if not self.logged_in:
                return {"success": False, "message": "请先登录"}
            
            show_id = config.get('show_id')
            session_id = config.get('session_id')
            price_range = config.get('price_range')
            ticket_count = config.get('ticket_count', 1)
            rush_time = config.get('rush_time')
            
            # 等待开抢时间
            if rush_time:
                target_time = datetime.fromisoformat(rush_time)
                now = datetime.now()
                if target_time > now:
                    wait_seconds = (target_time - now).total_seconds()
                    self.logger.info(f"等待开抢时间: {wait_seconds}秒")
                    time.sleep(max(0, wait_seconds))
            
            # 开始抢票
            self.logger.info("开始抢票流程")
            
            # 1. 进入演出页面
            self.driver.get(f"https://detail.damai.cn/item.htm?id={show_id}")
            time.sleep(2)
            
            # 2. 选择场次
            try:
                session_element = self.driver.find_element(
                    By.CSS_SELECTOR, f"[data-id='{session_id}']"
                )
                session_element.click()
                time.sleep(1)
            except:
                return {"success": False, "message": "场次选择失败"}
            
            # 3. 选择价位
            try:
                price_element = self.driver.find_element(
                    By.CSS_SELECTOR, f"[data-price='{price_range}']"
                )
                price_element.click()
                time.sleep(1)
            except:
                return {"success": False, "message": "价位选择失败"}
            
            # 4. 设置票数
            try:
                count_input = self.driver.find_element(By.CLASS_NAME, "count-input")
                count_input.clear()
                count_input.send_keys(str(ticket_count))
                time.sleep(1)
            except:
                pass
            
            # 5. 点击立即购买
            buy_button = self.wait.until(
                EC.element_to_be_clickable((By.CLASS_NAME, "buybtn"))
            )
            buy_button.click()
            
            # 6. 等待订单确认页面
            time.sleep(3)
            
            # 7. 提交订单
            if config.get('auto_submit', True):
                try:
                    submit_button = self.wait.until(
                        EC.element_to_be_clickable((By.CLASS_NAME, "submit-btn"))
                    )
                    submit_button.click()
                    
                    # 等待订单结果
                    time.sleep(5)
                    
                    # 检查订单状态
                    if "订单成功" in self.driver.page_source or "支付订单" in self.driver.page_source:
                        # 保存成功截图
                        screenshot_path = self.take_screenshot("order_success")
                        
                        return {
                            "success": True,
                            "message": "抢票成功",
                            "order_id": self.extract_order_id(),
                            "screenshot": screenshot_path
                        }
                    else:
                        return {"success": False, "message": "订单提交失败"}
                        
                except:
                    return {"success": False, "message": "订单提交超时"}
            
            return {"success": True, "message": "已添加到购物车"}
            
        except Exception as e:
            self.logger.error(f"抢票失败: {e}")
            screenshot_path = self.take_screenshot("rush_error")
            return {
                "success": False,
                "message": f"抢票失败: {str(e)}",
                "screenshot": screenshot_path
            }
    
    def extract_order_id(self) -> str:
        """提取订单号"""
        try:
            # 从页面URL或元素中提取订单号
            current_url = self.driver.current_url
            if "orderId=" in current_url:
                return current_url.split("orderId=")[1].split("&")[0]
            return ""
        except:
            return ""
    
    def take_screenshot(self, name: str) -> str:
        """截图保存"""
        try:
            # 创建截图目录
            screenshot_dir = Path("screenshots")
            screenshot_dir.mkdir(exist_ok=True)
            
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"{name}_{timestamp}.png"
            filepath = screenshot_dir / filename
            
            # 截图
            self.driver.save_screenshot(str(filepath))
            self.logger.info(f"截图已保存: {filepath}")
            
            return str(filepath)
            
        except Exception as e:
            self.logger.error(f"截图失败: {e}")
            return ""
    
    def get_monitor_data(self) -> Dict[str, any]:
        """获取监控数据"""
        return {
            "active_tasks": 0,
            "success_count": 0,
            "failed_count": 0,
            "total_tickets": 0,
            "logs": []
        }
    
    def close(self):
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()
            self.driver = None
            self.logged_in = False
            self.logger.info("浏览器已关闭")